/*
** Implement a (subset of) of C++ vector in C.
**
** Author: Andrew Turpin
** Date: Mon 29 Apr 2013 18:49:33 EST
**
*/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "vector.h"

// Create new, empty vector and return it
Vector * 
vector_new() {                   
    Vector *v = (Vector *)malloc(sizeof(Vector));
    assert(v != NULL);
    v->V       = NULL;
    v->size    = 0;
    v->maxSize = 0;
    return v;
}

// resize vector to maxSize == n
// If realloc fails
//    return VECTOR_SET_FAIL
// else
//    return VECTOR_SET_PASS
int 
vector_resize(Vector *v, int n) {                   
    assert(v != NULL);
    v->V = (void **)realloc(v->V, sizeof(void *) * n);
    if (v->V == NULL)
        return VECTOR_SET_FAIL;
    v->maxSize = n;                              
    return VECTOR_SET_PASS;
}

// return element i of vector v
// or NULL if outside v->size
void *
vector_get(Vector *v, int i) {
    assert(v != NULL);
    if (i >= v->size)
        return NULL;
    else
        return v->V[i];
}

// Add p onto the end of v, resizing if necessary.
// RETURNS: index of p in v, or -1 if failed.
int
vector_push_back(Vector *v, void *p) {
    assert(v != NULL);
    if (v->size >= v->maxSize) {
        if (vector_resize(v, v->size * 2 ) == VECTOR_SET_FAIL)
            return -1;
    } 
    v->V[v->size] = p;
    v->size++;
    return v->size - 1;
}

// return size (number of elements) == next available slot in array
int vector_size(Vector *v) { assert(v != NULL); return v->size; } 
